<script setup lang="ts">

import {Object3D} from "three";
import {ShallowRef} from "vue";
import {
  ActionType,
  ActionTypeList,
  ActionTypeDesc,
  EventObject,
  EventTypeDesc,
  EventTypeList
} from "@/types/web3d";
import {FormInstance} from "element-plus";
import ActionOpenDialog from './ActionOpenDialog.vue'
import ActionPlayAudio
  from "@/views/web3d/model/component/tool/edit/dialog/event/ActionPlayAudio.vue";

const message = useMessage()

const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const formType = ref<'create' | 'update'>('create')
const formData = ref({
  name: undefined,
  event: undefined,
  action: undefined,
  function: undefined,
  metadata: undefined,
})
const formRules = reactive({
  name: [{ required: true, message: '请输入事件命名', trigger: 'blur' }],
  event: [{ required: true, message: '请选择触发类型', trigger: 'change' }],
  action: [{ required: true, message: '请选择执行动作', trigger: 'change' }],
})
const isSave = ref(false)

// 当前编辑对象
const editObject = inject<ShallowRef<Object3D | null>>('editObject')!
const eventList = ref<EventObject[]>([])

/** 开启弹窗 */
const open = async () => {
  if (!editObject.value) {
    try {
      await message.confirm('当前编辑对象为空', '请选择要编辑的对象', 'error')
    } finally {
      close()
    }
  }
  reset()
  dialogVisible.value = true
  eventList.value = editObject.value?.userData.eventList || []
}
defineExpose({open})

/** 关闭弹窗 */
const close = () => {
  reset()
  dialogVisible.value = false
}

/** 重置表单 */
const reset = () => {
  formType.value = 'create'
  formData.value = {
    name: undefined,
    event: undefined,
    action: undefined,
    function: undefined,
    metadata: undefined,
  }
  formRef.value?.resetFields()
  currentEvent.value = null
  isSave.value = false
}

/** 添加事件 */
const handleAdd = async () => {
  if (actionRef.value && !isSave.value) {
    await message.confirm('当前事件暂未生成，是否确定切换')
  }
  reset()
}

/** 切换事件 */
const currentEvent = ref<EventObject | null>()
const handleCheck = async (eventObject: EventObject) => {
  if (actionRef.value && !isSave.value) {
    await message.confirm('当前事件暂未生成，是否确定切换')
  }
  reset()
  formData.value = {
    ...eventObject
  } as any
  formType.value = 'update'
  currentEvent.value = eventObject
}

/** 删除事件 */
const handleRemove = (eventObject: EventObject) => {
  eventList.value.splice(eventList.value.indexOf(eventObject), 1)
  if (currentEvent.value === eventObject) {
    reset()
  }

  message.success('删除事件成功')
}

/** 动作事件 */
const actionRef = ref()
// 生成事件
const generateEvent = async () => {
  await formRef.value!.validate()

  if (formType.value === 'create') {
    const eventObject = actionRef.value!.generateEvent() as EventObject
    eventList.value.push({
      ...formData.value,
      function: eventObject?.function || formData.value?.function,
      metadata: eventObject?.metadata
    } as any)

    reset()
    message.success('添加事件成功')
  } else {
    const event = currentEvent.value
    event!.name = formData.value.name
    event!.event = formData.value.event
    event!.action = formData.value.action

    const eventObject = actionRef.value!.generateEvent() as EventObject
    event!.function = eventObject?.function || formData.value?.function
    event!.metadata = eventObject?.metadata

    reset()
    message.success('修改事件成功')
  }

  isSave.value = true
}

/** 提交修改 */
const submit = async () => {
  if (actionRef.value && !isSave.value) {
    await message.confirm('当前事件暂未生成，是否确定保存')
  }
  editObject.value!.userData.eventList = eventList.value
  close()
  message.success('保存事件成功，注意及时保存模型')
}

</script>

<template>
  <Dialog v-model="dialogVisible" title="添加事件" width="90%">
    <el-row :gutter="8">
      <el-col :span="6">
        <ContentWrap>
          <el-button type="primary" @click="handleAdd">添加事件</el-button>
          <div class="text-center m-4 font-bold" v-if="eventList.length === 0">
            当前暂无事件
          </div>
          <el-table :data="eventList"  v-else>
            <el-table-column label="事件名称" prop="name" align="center" />
            <el-table-column label="动作类型" prop="action" align="center">
              <template #default="scope">
                {{ActionTypeDesc[scope.row.action]}}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button type="primary" link @click="handleCheck(scope.row)">修改</el-button>
                <el-button type="danger" link @click="handleRemove(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </ContentWrap>
      </el-col>
      <el-col :span="18">
        <ContentWrap>
          <div class="mb-4 ml-4" v-if="formData.action">
            <el-button type="primary" @click="generateEvent">生成事件</el-button>
          </div>
          <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100">
            <el-form-item label="事件命名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入事件名称" />
            </el-form-item>
            <el-form-item label="触发类型" prop="event">
              <el-radio-group v-model="formData.event">
                <el-radio-button
                  v-for="(item, index) in EventTypeList"
                  :key="index"
                  :label="EventTypeDesc[item]"
                  :value="item"
                />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="执行动作" prop="action">
              <el-radio-group v-model="formData.action">
                <el-radio-button
                  v-for="(item, index) in ActionTypeList"
                  :key="index"
                  :label="ActionTypeDesc[item]"
                  :value="item"
                />
              </el-radio-group>
            </el-form-item>

            <el-form-item
              v-if="formData.action === ActionType.OPEN_DIALOG"
              label="展示资源"
              prop="metadata"
            >
              <ActionOpenDialog
                ref="actionRef"
                :key="formData.metadata"
                :metadata="formData.metadata"
              />
            </el-form-item>

            <el-form-item
              v-else-if="formData.action === ActionType.PLAY_AUDIO"
              label="所选音频"
              prop="metadata"
            >
              <ActionPlayAudio
                ref="actionRef"
                :key="formData.metadata"
                :metadata="formData.metadata"
              />
            </el-form-item>
          </el-form>
        </ContentWrap>
      </el-col>
    </el-row>

    <template #footer>
      <el-button type="primary" @click="submit">保存事件</el-button>
    </template>
  </Dialog>
</template>

<style scoped lang="scss">

</style>
